package com.ijiuchuang.jc_localization.ble;

import android.bluetooth.BluetoothDevice;

import com.ijiuchuang.jc_localization.bean.event.BeaconEvent;
import com.ijiuchuang.jc_localization.tools.utils.Log;

import org.greenrobot.eventbus.EventBus;

import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/4/13
 */
public class iBeaconClass {

    /**
     * 广播内容
     * 0x09,   // length of this data 9byte
     * GAP_ADTYPE_MANUFACTURER_SPECIFIC,
     * 0x4E, 0x4D, 0x52, 0x5B,    chzu编号
     * 0x01,  编号                                  0手环 1卧室 2厨房
     * 0x12,  温度
     * 0x83,  湿度
     * 0x66,  心率
     */

    private final static String TAG = "iBeaconClass";

    public static BeaconEvent getBeacon(BluetoothDevice device, int rssi, byte[] scanData) {
        int startByte = 2;
        //是否为 iBeacon
        boolean patternFound = false;

        // 判断是否为IBeacon
        while (startByte <= 5) {
            if (((int) scanData[startByte + 2] & 0xff) == 0x52
                    && ((int) scanData[startByte + 3] & 0xff) == 0x1B) {
                // yes! This is an iBeacon
                patternFound = true;
                break;
            }
            startByte++;
        }

        BeaconEvent iBeacon = new BeaconEvent();
        iBeacon.power = (int) scanData[startByte + 4];
        iBeacon.heartRate = (int) scanData[startByte + 5];
        iBeacon.humidity = (int) scanData[startByte + 6];
        iBeacon.number = (int) scanData[startByte + 7];
        iBeacon.rssi = rssi;
        iBeacon.device = device;
        if (device != null) {
            iBeacon.bluetoothAddress = device.getAddress();
            iBeacon.name = device.getName();
        }
        iBeacon.isIbeacon = patternFound;
        return iBeacon;
    }

    //  处理广播数据
    public static void dataProcessing(BluetoothDevice device, int rssi, byte[] scanData) {

        BeaconEvent iBeacon = getBeacon(device, rssi, scanData);

        // 若为IBeacon则将这个数据发送出去,在需要的地方自行处理
        if (iBeacon.isIbeacon) {
            // 打印
            // FIXME: 2016/5/5 关闭打印 需要时再打开
            Log.i("mac: " + iBeacon.bluetoothAddress +
                    ",Rssi: " + iBeacon.rssi +
                    ",number: " + iBeacon.number +
                    ",heartRate: " + iBeacon.heartRate +
                    ",power: " + iBeacon.power +
                    ",humidity: " + iBeacon.humidity);
            // RxJava 切换线程 在后台分发事件
            Observable.just(iBeacon)
                    .subscribeOn(Schedulers.io()) // 在 IO 线程处理数据
                    .observeOn(Schedulers.io()) // 在 IO 线程发送事件
                    .subscribe(new Action1<BeaconEvent>() {
                        @Override
                        public void call(BeaconEvent beaconEvent) {
                            // 事件分发
                            EventBus.getDefault().post(beaconEvent);
                        }
                    });
        }
    }
}
